import arcade

TILE_SCALING = 0.5
SPRITE_SCALING_PLAYER = 0.5

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

MOVE_SPEED = 5  # 移动速度
GRAVITY = 0.3
JUMP_SPEED = 10


class MyGame(arcade.Window):
    """ 继承Window类的游戏类, 表示游戏窗口"""

    def __init__(self):
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, "精灵与墙")
        self.player_list = None
        self.wall_list = None

        self.player = None

        self.physics_engine = None
        self.player_camera = arcade.Camera(SCREEN_WIDTH, SCREEN_HEIGHT)
        self.info_camera = arcade.Camera(SCREEN_WIDTH, SCREEN_HEIGHT)

    def setup(self):
        # 设置背景颜色
        arcade.set_background_color(arcade.color.AMAZON)

        self.player_list = arcade.SpriteList()
        self.wall_list = arcade.SpriteList()

        self.player = arcade.Sprite(":resources:images/animated_characters/male_adventurer/maleAdventurer_idle.png",
                                    SPRITE_SCALING_PLAYER)
        self.player.center_x = 50
        self.player.center_y = 64
        self.player_list.append(self.player)

        # 从tile map文件中加载wall_list对象
        map_name = "test.json"
        self.tile_map = arcade.load_tilemap(map_name, scaling=TILE_SCALING)

        self.wall_list = self.tile_map.sprite_lists["Walls"]

        if self.tile_map.background_color:
            arcade.set_background_color(self.tile_map.background_color)

        # 创建物理引擎
        # 传入玩家精灵，以及不能穿越的砖块列表
        self.physics_engine = arcade.PhysicsEnginePlatformer(self.player, self.wall_list, gravity_constant=GRAVITY)

    def on_key_press(self, key, modifiers):
        if key == arcade.key.SPACE or key == arcade.key.UP:
            # 检查是否有起跳点(很明显，你的角色还没学会二段跳，不能在半空跳跃)
            if self.physics_engine.can_jump():
                self.player.change_y = JUMP_SPEED
        elif key == arcade.key.LEFT:
            self.player.change_x = - MOVE_SPEED
        elif key == arcade.key.RIGHT:
            self.player.change_x = MOVE_SPEED

    def on_key_release(self, key, modifiers):
        if key == arcade.key.UP or key == arcade.key.DOWN:
            self.player.change_y = 0
        elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
            self.player.change_x = 0

    def on_draw(self):
        arcade.start_render()

        self.player_camera.use()
        self.player_list.draw()
        self.wall_list.draw()

        self.info_camera.use()
        arcade.draw_text("Score: 0", 10, 10, arcade.color.WHITE, 24)

    def update(self, delta_time):
        self.physics_engine.update()

        # 镜头移动速度，取值[0, 1]之间
        CAMERA_SPEED = 1
        # 镜头位置
        lower_left_corner = (self.player.center_x - self.width / 2,
                             self.player.center_y - self.height / 2)

        self.player_camera.move_to(lower_left_corner, CAMERA_SPEED)

def main():
    window = MyGame()
    window.setup()
    arcade.run()

if __name__ == "__main__":
    main()

